package com.linmu.utils;

import cn.apiclub.captcha.Captcha;
import cn.apiclub.captcha.backgrounds.GradiatedBackgroundProducer;
import cn.apiclub.captcha.gimpy.FishEyeGimpyRenderer;
import com.linmu.config.MyCaptchaConfig;
import org.springframework.stereotype.Repository;

/**
 * @author admin
 * @version 1.0.0
 * @ClassName CaptchaUtil.java
 * @Description 验证码工具类
 * @createTime 2022年02月06日 16:32:00
 */
@Repository
public class CaptchaUtil {
    private final RedisUtil redisUtil;
    private final MyCaptchaConfig captchaConfig;


    public CaptchaUtil(RedisUtil redisUtil, MyCaptchaConfig captchaConfig) {
        this.redisUtil = redisUtil;
        this.captchaConfig = captchaConfig;
    }

    public Captcha createCaptcha(String captchaUuid) {
        // 生成验证码
        Captcha captcha = new Captcha.Builder(captchaConfig.getCaptchaWidth(), captchaConfig.getCaptchaHeight())
                .addText().addBackground(new GradiatedBackgroundProducer())
                .gimp(new FishEyeGimpyRenderer())
                .build();
        redisUtil.set(captchaUuid,captcha.getAnswer(), captchaConfig.getCaptchaExpires());
        return captcha;
    }

    public boolean checkCaptcha(String captchaUuid,String captchaAns) {
        String realAns = (String) redisUtil.get(captchaUuid);
        return realAns.equals((captchaAns));
    }
}
